package com.dg.gaming.api.common.util
{
	import com.ericfeminella.collections.HashMap;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;

	[Event(name=LoaderCollectionEvent.ALLLOADERCOMPLETED, type="LoaderCollectionEvent")]

	public class LoaderCollection extends EventDispatcher
	{
		private var size:int=0;
		private var colpletedsize:int=0;
		private var _loadedArray:HashMap=new HashMap();

		public function LoaderCollection(sourceList:HashMap=null)
		{
			if (sourceList != null)
				init(sourceList);
		}

		public function init(sourceList:HashMap):void
		{
			var keys:Array=sourceList.getKeys();
			var len:int=keys.length;
			size=len;
			for (var i:int=0; i < len; i++)
			{
				var loader:Loader=new Loader();
				loader.name=keys[i];
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completed);
				loader.contentLoaderInfo.addEventListener("ioError", error);
				loader.contentLoaderInfo.addEventListener("securityError", error);
				var value:String=loader.name;
				value=sourceList.getValue(value);
				loader.load(new URLRequest(value));
			}

		}

		private function checkForCompleted():void
		{
			if (colpletedsize == size)
			{
//				var dataSortField:SortField=new SortField();
//				dataSortField.name="index";
//				dataSortField.numeric=true;
//				var numericDataSort:Sort=new Sort();
//				numericDataSort.fields=[dataSortField];
//
//				_loadedArray.sort=numericDataSort;
//				_loadedArray.refresh();
				dispatchEvent(new LoaderCollectionEvent(_loadedArray));
			}
		}

		private function completed(event:Event):void
		{
			var content:Bitmap=Bitmap(event.currentTarget.content);
			var key:String=event.currentTarget.loader.name;
			_loadedArray.put(key, content.bitmapData.clone());
			colpletedsize++;
			checkForCompleted();
		}

		private function error(event:Event):void
		{
			colpletedsize++;
////			_loadedArray[]=new BitmapData(0, 0);
//			var key:String=event.currentTarget.loader.name;
//			_loadedArray.put(key, new BitmapData(1, 1));
			checkForCompleted();
		}





	}
}